package br.com.medvagas.web.conversor;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

import org.apache.commons.lang.StringUtils;

@FacesConverter("conversorTelefone")
public class ConversorTelefone implements Converter {
	
	@Override
	public String getAsString(FacesContext FacesContext, UIComponent UIComponent, Object valor) 
			throws ConverterException {
		
		String valorString = (String) valor;
		if (StringUtils.isNotEmpty(valorString) && valorString.length() == 10) {
			return valorString.substring(0, 2) + "-"
					+ valorString.substring(2, 6) + "-"
					+ valorString.substring(6);
		}
		return valor.toString();
	}

	@Override
	public Object getAsObject(FacesContext FacesContext, UIComponent UIComponent, String novoValor) 
			throws ConverterException {
		return novoValor != null ? novoValor.replaceAll("-", "") : null;
	}

}